package es.uned.hoomgle.core.services.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import es.uned.hoomgle.hibernate.beans.interfaces.RoleI;
import es.uned.hoomgle.hibernate.beans.interfaces.UserI;


@Service("assembler")
/**
 * 
 * Transforma un usuario de base de datos en un usuario de spring security
 *
 */
public class Assembler {

  @Transactional(readOnly = true)
  /**
   * Transforma un usuario de base de datos en un usuario de spring security
   * @param userEntity
   * @return
   */
  public User buildUserFromUserEntity(UserI userEntity) {

    String username = userEntity.getName();
    String password = userEntity.getPassword();
    boolean enabled = userEntity.isActive();
    boolean accountNonExpired = userEntity.isActive();
    boolean credentialsNonExpired = userEntity.isActive();
    boolean accountNonLocked = userEntity.isActive();

    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    for (Object roleObject : userEntity.getRoles()) {
    	RoleI role = (RoleI)roleObject;
      authorities.add(new SimpleGrantedAuthority(role.getName()));
    }

    User user = new User(username, password, enabled,
      accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
    return user;
  }
}
